package com.example.musicdemo.base

import android.content.Context
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.example.musicdemo.widget.LoadMoreView

abstract class BaseListAdapter<ITEM_BEAN, ITEM_VIEW : View> :
    RecyclerView.Adapter<BaseListAdapter.BaseListHolder>() {
    private var list = ArrayList<ITEM_BEAN>()
    private var listener: ((list: ArrayList<ITEM_BEAN>, position: Int) -> Unit)? = null
    private var mLongListener: ((list: ArrayList<ITEM_BEAN>, position: Int,itemView:View) -> Unit)? = null

    /**
     *  更新数据
     */
    fun updateList(list: List<ITEM_BEAN>?) {
        list?.let {
            this.list.clear()
            this.list.addAll(list)
            notifyDataSetChanged()
        }
    }


    /**
     * 加载更多
     */
    fun loadMore(list: List<ITEM_BEAN>?) {
        list?.let {
            this.list.addAll(list)
            notifyDataSetChanged()
        }
    }


    override fun onBindViewHolder(holder: BaseListHolder, position: Int) {
        //如果是最后一条数据的话就没有必要刷新数据
        if (position == list.size) return
        val data = list[position]
        val itemView = holder?.itemView as ITEM_VIEW
        //条目刷新

        refreshItemView(itemView, data)

        itemView.setOnClickListener {
            listener?.let {
                it(list, position)
            }
        }

        if (mLongListener != null) {
            itemView.setOnLongClickListener(View.OnLongClickListener {
                (mLongListener!!)(list, position,itemView)
                false
            })


        }
    }


    abstract fun refreshItemView(itemView: ITEM_VIEW, data: ITEM_BEAN)


    override fun getItemCount(): Int {
        return list.size + 1

    }

    override fun getItemViewType(position: Int): Int {
        if (position == list.size) {
            return 1
        } else {
            return 0
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BaseListHolder {
        if (viewType == 1) {
            //最后一条
            return BaseListHolder(LoadMoreView(parent?.context))
        } else {
            //普通条目
            val itemView: View = getItemView(parent?.context)

            return BaseListHolder(itemView)
        }
    }

    abstract fun getItemView(context: Context?): ITEM_VIEW


    open fun setMyListener(listener: (list: ArrayList<ITEM_BEAN>, position: Int) -> Unit) {
        this.listener = listener
    }

    open fun setLongListener(longListener: (list: ArrayList<ITEM_BEAN>, position: Int,itemView:View) -> Unit) {
        this.mLongListener = longListener
    }


    class BaseListHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {

    }


}